<!-- 企业编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="1000"
    :model-value="modelValue"
    title="收款详情"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="应收金额"> {{ rebatAmount }}元 </el-form-item>
      <el-form-item label="实际收款" prop="refund_amount_paid">
        <el-input
          v-model="form.amount"
          style="width: 150px"
          :disabled="form.status == 200"
        >
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="收款时间" prop="pay_time">
        <el-date-picker
          v-model="form.pay_time"
          class="filter-item"
          type="datetime"
          placeholder="收款时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 230px"
          :disabled="form.status == 200"
        />
      </el-form-item>
      <el-form-item label="收款凭证" prop="images">
        <image-upload
          :limit="100"
          v-model="form.images"
          :read-only="form.status == 200"
      /></el-form-item>
      <el-form-item label=" " v-if="form.status == 0">
        <el-button type="primary" :loading="loading" @click="save">
          复核完成
        </el-button>
      </el-form-item>
    </el-form>
    <el-table :data="insuranceList" border stripe>
      <el-table-column prop="plate_number" label="车牌号" />
      <el-table-column prop="insurance" label="保险公司" width="100" />
      <el-table-column prop="cate" label="类型" width="80" />
      <el-table-column prop="price" label="出单金额" width="90" />
      <el-table-column prop="rebate" label="返点" width="70" />
      <el-table-column prop="rebate_amount" label="返点金额" width="90" />
      <el-table-column prop="rebate_amount_paid" label="实收金额" width="90" />
      <el-table-column prop="rebate_pay_time" label="收款时间" width="165" />
    </el-table>
  </ele-modal>
</template>

<script setup>
  import { ref, watch, reactive, computed } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { rebatePay, getPayRecordById } from '@/api/company';
  import ImageUpload from '@/components/ImageUpload/index.vue';

  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object
  });

  /** 表单实例 */
  const formRef = ref(null);

  const loading = ref(false);

  /** 表单验证规则 */
  const rules = reactive({
    images: [
      {
        required: true,
        message: '请上传付款图片',
        type: 'string',
        trigger: 'blur'
      }
    ],
    rebate_time: [
      {
        required: true,
        message: '请输入收款时间',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /** 保存编辑 */
  const save = () => {
    console.log(form);
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;

      let list = JSON.stringify(insuranceList.value);
      rebatePay({
        id: form.value.id,
        action: '复核',
        list,
        pay_time: form.value.pay_time,
        images: form.value.images,
        rebate_amount_paid: form.value.amount
      })
        .then(() => {
          loading.value = false;
          EleMessage.success('操作成功');
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };

  const rebatAmount = computed(() => {
    const totalRebate =
      insuranceList.value.reduce((total, item) => {
        // 将金额转换为数字后累加，并乘以 100 以避免精度问题
        return total + Math.round(parseFloat(item.rebate_amount || 0) * 100);
      }, 0) / 100; // 最后除以 100 恢复原始金额

    return totalRebate.toFixed(2);
  });

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  const insuranceList = ref([]);
  const form = ref([]);

  const getPayRecord = () => {
    getPayRecordById({ id: props.data.id, relationType: '返点收入' })
      .then((res) => {
        form.value = res.payRecord;
        insuranceList.value = res.relationData;
      })
      .catch((e) => {
        EleMessage.error(e.message);
      });
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        getPayRecord();
      } else {
        console.log('无');
      }
    }
  );
</script>
